package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.MqOpsService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class UserAccountReceiver {
    @Autowired
    private MqOpsService mqOpsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(
                    value = MqConst.EXCHANGE_ACCOUNT,
                    durable = "true"
            ),
            value = @Queue(
                    value = MqConst.QUEUE_USER_REGISTER,
                    durable = "true",
                    exclusive = "false"
            ),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void listenUserAccountInit(String userId, Message message, Channel channel){
        // 1.获取消息，进行判断
        if (!StringUtils.hasText(userId)) {
            return;
        }
        // 2.消费消息
        mqOpsService.userAccountInit(userId);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 3.手动应答
        channel.basicAck(deliveryTag,false);
    }
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(
                    value = MqConst.EXCHANGE_ACCOUNT,
                    durable = "true"
            ),
            value = @Queue(
                    value = MqConst.QUEUE_ACCOUNT_MINUS,
                    durable = "true",
                    exclusive = "false"
            ),
            key = MqConst.ROUTING_ACCOUNT_MINUS
    ))
    @SneakyThrows
    public void minus(String content, Message message, Channel channel) {
        // 1.获取消息，进行判断
        if (!StringUtils.hasText(content)) {
            return;
        }

        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.minus(content);
            // 3.发送消息给本地消息表
            rabbitService.sendMessage(MqConst.EXCHANGE_LOCAL_MSG, MqConst.ROUTING_LOCAL_MSG, content);
            // 4.手动应答
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            // 重试 消息继续能够被消费者消费

            String retryMsgKey = "retry:msg:" + content;
            Long count = redisTemplate.opsForValue().increment(retryMsgKey);
            if (count >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            channel.basicNack(deliveryTag, false, false);
        }
    }
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(
                    value = MqConst.EXCHANGE_ACCOUNT,
                    durable = "true"
            ),
            value = @Queue(
                    value = MqConst.QUEUE_ACCOUNT_UNLOCK,
                    durable = "true",
                    exclusive = "false"
            ),
            key = MqConst.ROUTING_ACCOUNT_UNLOCK
    ))
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ACCOUNT_UNLOCK, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ACCOUNT),
            key = MqConst.ROUTING_ACCOUNT_UNLOCK))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void unLock(String content, Message message, Channel channel) {
        // 1.获取消息，进行判断
        if (StringUtils.isEmpty(content)) {
            return;
        }

        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.unLock(content);
            // 3.发送消息给本地消息表
            rabbitService.sendMessage(MqConst.EXCHANGE_LOCAL_MSG, MqConst.ROUTING_LOCAL_MSG, content);
            // 4.手动应答
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            // 重试 消息继续能够被消费者消费

            String retryMsgKey = "retry:msg:" + content;
            Long count = redisTemplate.opsForValue().increment(retryMsgKey);
            if (count >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
